package com.bocai.grainshop.ware.service.impl;

import com.bocai.common.constant.WareConstant;
import com.bocai.grainshop.ware.entity.PurchaseDetailEntity;
import com.bocai.grainshop.ware.service.PurchaseDetailService;
import com.bocai.grainshop.ware.service.WareSkuService;
import com.bocai.grainshop.ware.vo.MergeVo;
import com.bocai.grainshop.ware.vo.PurchaseDoneVo;
import com.bocai.grainshop.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bocai.common.utils.PageUtils;
import com.bocai.common.utils.Query;

import com.bocai.grainshop.ware.dao.PurchaseDao;
import com.bocai.grainshop.ware.entity.PurchaseEntity;
import com.bocai.grainshop.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;



@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnrecelivePage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        //如果为空就新建一个
        if(purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //有就合并采购单
        List<Long> items = mergeVo.getItems();
        Collection<PurchaseDetailEntity> list = purchaseDetailService.listByIds(items);
        List<PurchaseDetailEntity> entities = list.stream().filter(obj -> {
            if (obj.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() ||
                    obj.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()) {
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());

        if(entities.size() == list.size()){
            Long findPurchaseId = purchaseId;
            List<PurchaseDetailEntity> collect = items.stream().map(obj -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(obj);
                entity.setPurchaseId(findPurchaseId);
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                return entity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);

            PurchaseEntity entity = new PurchaseEntity();
            entity.setId(purchaseId);
            entity.setUpdateTime(new Date());
            this.updateById(entity);
        }
    }

    @Override
    public void received(List<Long> ids) {
        //1.判断当前采购单是否时新建还是已分配
        List<PurchaseEntity> collect = ids.stream().map(obj -> {
            PurchaseEntity byId = this.getById(obj);
            return byId;
        }).filter((f) -> {
            if (f.getStatus() == WareConstant.PurchaseStatusEnum.CREATE.getCode() ||
                    f.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            } else {
                return false;
            }
        }).map((obj)->{
            obj.setStatus(WareConstant.PurchaseStatusEnum.RECRIVE.getCode());
            obj.setUpdateTime(new Date());
            return obj;
        }).collect(Collectors.toList());

        //修改采购单状态
        this.updateBatchById(collect);

        //修改采购项的状态
        collect.forEach(Purch -> {
            List<PurchaseDetailEntity> Entities = purchaseDetailService.listDetailByPurchaseId(Purch.getId());
            List<PurchaseDetailEntity> entityList = Entities.stream().map(obj -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(obj.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(entityList);
        });
    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {
        //改变采购项状态
        Boolean flag = true;
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        for (PurchaseItemDoneVo item : items){
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                entity.setStatus(item.getStatus());
            }else {
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //将成功采购的入库
                PurchaseDetailEntity id = purchaseDetailService.getById(item.getItemId());

                wareSkuService.savaPurchase(id.getSkuId(),id.getWareId(),id.getSkuNum());
            }
            entity.setId(item.getItemId());
            updates.add(entity);
        }
        purchaseDetailService.updateBatchById(updates);

        //修改采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        Long id = doneVo.getId();
        purchaseEntity.setId(id);
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setStatus(flag == false ? WareConstant.PurchaseStatusEnum.HASERROR.getCode():
                WareConstant.PurchaseStatusEnum.FINISH.getCode());
        this.updateById(purchaseEntity);

    }

}